// 向页面注入JS
function injectCustomJs(jsPath) {
    jsPath = jsPath || 'js/inject.js';
    console.log(jsPath);
    var temp = document.createElement('script');
    temp.setAttribute('type', 'text/javascript');
    // 获得的地址类似：chrome-extension://ihcokhadfjfchaeagdoclpnjdiokfakg/js/inject.js
    temp.src = chrome.extension.getURL(jsPath);
    temp.onload = function () {
        // 放在页面不好看，执行完后移除掉
        this.parentNode.removeChild(this);
    };
    document.body.appendChild(temp);
}

// 接收来自popup的消息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    console.log('收到消息：');
    console.log(request, sender, sendResponse);

    switch (request.cmd) {
        case 'login':
            sendResponse({ status: 1, message: '开始执行：跳转到用户登录页面' });
            window.location.href = 'https://plogin.m.jd.com/login/login';
            break;

        case 'start':
            sendResponse({ status: 1, message: '开始执行：循环下单' });
            chrome.storage.local.set({ myRunning: 1 });
            window.location.href = 'https://jd.com';
            break;

        case 'stop':
            sendResponse({ status: 1, message: '开始执行：停止下单' });
            chrome.storage.local.set({ myRunning: 0 });
            break;

        default:
            sendResponse({ status: 1, message: '未知的命令！' });
            break;
    }
});

var goodsId; // 商品链接uri
var goodsTagKey; // 商品标签第几个
chrome.storage.local.get({ myUrl: '', myGoodsTagKey: 0 }, function (items) {
    goodsId = items.myUrl.match('[0-9]*(?=\.html)')[0];
    goodsTagKey = items.myGoodsTagKey;
});

function buy() {
    switch (window.location.pathname) {
        case '/product/' + goodsId + '.html': // 商品页
            $('#buyBtn2').click();
            $('#skuPop1 .item').eq(goodsTagKey).click();
            setInterval(() => $('#buyBtn1').click(), 1000);
            break;

        case '/deal/confirmorder/main': // 下单页
            injectCustomJs('js/injects/pay.js');
            break;

        case '/norder/freeRegister.action': // 快捷下单页
            window.location.href = 'https://plogin.m.jd.com/login/login';
            break;

        case '/login/login': // 登录页
            // injectCustomJs('js/jquery-1.11.0.min.js');
            // injectCustomJs('js/injects/login.js');
            alert('请先登录！');
            break;

        case '/cpay/newPay-index.html': // 支付页
        default:
            // chrome.storage.local.get({ myUrl: 'about:blank' }, function (items) {
            //     window.location.href = items.myUrl;
            // });
            window.location.href = 'https://item.m.jd.com/product/' + goodsId + '.html';
            break;
    }
}

// 此代码需写在最后
// 根据myRunning判断是否注入采购js
chrome.storage.local.get({ myRunning: 0 }, function (items) {
    if (items.myRunning === 1) {
        buy();
    }
});
